package com.bysj.sausys.service.impl;

import com.bysj.sausys.beans.PageQuery;
import com.bysj.sausys.beans.PageResult;
import com.bysj.sausys.beans.Pagination;
import com.bysj.sausys.beans.SubmitTaskBean;
import com.bysj.sausys.common.AssConst;
import com.bysj.sausys.common.UserConst;
import com.bysj.sausys.common.WorkFlowConst;
import com.bysj.sausys.dao.SysAssAnnMapper;
import com.bysj.sausys.exception.ParamException;
import com.bysj.sausys.model.SysAssAnn;
import com.bysj.sausys.service.ISysAssAnnService;
import com.bysj.sausys.service.ISysAssService;
import com.bysj.sausys.service.ISysUserService;
import com.bysj.sausys.service.ISysWorkFlowService;
import com.bysj.sausys.util.ObjectUtils;
import com.bysj.sausys.util.PropertiesUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 社团年审申请Service接口实现
 *
 * @author WangZK
 */
@Service("sysAssAnnService")
public class SysAssAnnServiceImpl implements ISysAssAnnService {

    @Resource
    private SysAssAnnMapper sysAssAnnMapper;
    @Resource
    private ISysWorkFlowService sysWorkFlowService;
    @Resource
    private ISysUserService sysUserService;
    @Resource
    private ISysAssService sysAssService;

    /**
     * 保存社团年审申请单
     *
     * @param sysAssAnn
     * @param map
     */
    @Override
    public void save(SysAssAnn sysAssAnn, Map map) {
        sysAssAnn.setAssId(UserConst.getCurrentAssId(map));
        sysAssAnn.setInsertMan(UserConst.getCurrentUsername(map));
        sysAssAnn.setInsertTime(new Date());
        sysAssAnnMapper.insertSelective(sysAssAnn);
    }

    /**
     * 更新社团年审申请单
     *
     * @param sysAssAnn
     * @param map
     */
    @Override
    public void update(SysAssAnn sysAssAnn, Map map) {
        SysAssAnn before = sysAssAnnMapper.selectByPrimaryKey(sysAssAnn.getId());
        if (AssConst.NON_EDITABLE.getCode().equals(before.getEditStatus())) {
            throw new ParamException("社团活动申请单为不可编辑状态，编辑失败");
        }
        if (before == null) {
            throw new ParamException("待更新的社团活动申请单不存在");
        }

        SysAssAnn after = new SysAssAnn();

        after.setId(sysAssAnn.getId());
        after.setAssId(UserConst.getCurrentAssId(map));
        after.setAssSize(sysAssAnn.getAssSize());
        after.setAssMemberComp(sysAssAnn.getAssMemberComp());
        after.setAnnFilename(sysAssAnn.getAnnFilename());
        after.setAnnFile(sysAssAnn.getAnnFile());
        after.setInstructSituation(sysAssAnn.getInstructSituation());
        after.setLastupdMan(UserConst.getCurrentUsername(map));
        after.setLastupdTime(new Date());
        sysAssAnnMapper.updateByPrimaryKeySelective(after);
    }

    /**
     * 根据id获取社团年审申请单
     *
     * @param id
     * @return
     */
    @Override
    public SysAssAnn findById(Integer id) {
        return sysAssAnnMapper.selectByPrimaryKey(id);
    }

    /**
     * 分页获取社团年审申请单列表
     *
     * @param pageQuery
     * @param map
     * @return
     */
    @Override
    public PageResult<SysAssAnn> getPage(PageQuery pageQuery, Map map) {
        Integer assId = UserConst.getCurrentAssId(map);
        if (assId == -1) {
            return getPageForAuditComp(pageQuery);
        } else {
            return getPageByAssId(pageQuery, assId);
        }
    }

    /**
     * 分页获取审批完成的社团年审列表
     *
     * @param pageQuery
     * @return
     */
    private PageResult<SysAssAnn> getPageForAuditComp(PageQuery pageQuery) {
        int count = sysAssAnnMapper.countByAuditStatus(AssConst.ASS_ANN_AUDIT_PASS.getCode());
        if (count > 0) {
            List<SysAssAnn> sysAssAnnList = sysAssAnnMapper.selectByAuditStatus(AssConst.ASS_ANN_AUDIT_PASS.getCode(), pageQuery);
            PageResult result = new PageResult();
            result.setList(sysAssAnnList);
            Pagination pagination = new Pagination();
            pagination.setTotal(count);
            pagination.setPageSize(pageQuery.getPageSize());
            pagination.setCurrentPage(pageQuery.getPageNo());
            result.setPagination(pagination);
            return result;
        }
        return new PageResult<>();
    }

    /**
     * 根据社团id分页获取社团年审列表
     */
    private PageResult<SysAssAnn> getPageByAssId(PageQuery pageQuery, Integer assId) {
        int count = sysAssAnnMapper.countByAssId(assId);
        if (count > 0) {
            List<SysAssAnn> sysAssAnnList = sysAssAnnMapper.getPageByAssId(pageQuery, assId);
            PageResult result = new PageResult();
            result.setList(sysAssAnnList);
            Pagination pagination = new Pagination();
            pagination.setTotal(count);
            pagination.setPageSize(pageQuery.getPageSize());
            pagination.setCurrentPage(pageQuery.getPageNo());
            result.setPagination(pagination);
            return result;
        }
        return new PageResult<>();
    }

    /**
     * 删除社团年审申请单
     *
     * @param id
     */
    @Override
    public void delete(Integer id) {
        SysAssAnn sysAssAnn = sysAssAnnMapper.selectByPrimaryKey(id);
        if (sysAssAnn == null) {
            throw new ParamException("社团年审申请单不存在，删除失败");
        }
        if (AssConst.NON_DELETING.getCode().equals(sysAssAnn.getDeleteStatus())) {
            throw new ParamException("社团年审申请单为不可删除状态，删除失败");
        }
        sysAssAnnMapper.deleteByPrimaryKey(id);
    }

    /**
     * 启动社团年审审批流程
     *
     * @param id
     * @param username
     */
    @Override
    public void saveStartProcess(Integer id, String username) {
        SysAssAnn sysAssAnn = sysAssAnnMapper.selectByPrimaryKey(id);
        if (sysAssAnn == null) {
            throw new ParamException("社团年审申请单不存在，启动流程失败");
        }
        if (!AssConst.ASS_ANN_INIT_ENTRY.getCode().equals(sysAssAnn.getAuditStatus())) {
            throw new ParamException("流程已启动，不需要再次启动");
        }

        //调用工作流的service，执行启动流程实例，让启动的流程实例关联业务的操作
        //1.通过配置文件获取流程定义的key
        String key = PropertiesUtil.getProperty(WorkFlowConst.ASS_ANN_KEY.getCode());
        //2.设置字符串
        String objId = sysAssAnn.getClass().getSimpleName() + "." + id;

        String processInstanceId = sysWorkFlowService.saveStartProcess(key, objId, username);

        if (processInstanceId == null || "".equals(processInstanceId)) {
            throw new ParamException("启动社团年审审批流程失败");
        }

        //更改推文的状态
        Map map = new HashMap(4);
        map.put("id", id);
        map.put("deleteStatus", AssConst.NON_DELETING.getCode());
        map.put("editStatus", AssConst.NON_EDITABLE.getCode());
        map.put("auditStatus", AssConst.ASS_ANN_AUDITING.getCode());
        sysAssAnnMapper.updateStatus(map);
    }

    /**
     * 获取审批信息
     *
     * @param taskId
     * @return
     */
    @Override
    public Map getAuditInfo(String taskId) {
        // 获取连线信息和历史审核人信息
        Map<String, Object> map = sysWorkFlowService.getAuditInfo(taskId);

        /**
         * 获取业务数据
         * 1.获取数据id
         * 2.根据id获取业务数据
         */
        int id = sysWorkFlowService.getBusinessIdByTaskId(taskId);
        SysAssAnn sysAssAnn = sysAssAnnMapper.selectByPrimaryKey(id);
        if (sysAssAnn == null) {
            throw new ParamException("获取社团年审申请单失败");
        }
        try {
            Map objectMap = ObjectUtils.objectToMap(sysAssAnn);
            objectMap.remove("insertTime");
            objectMap.remove("insertMan");
            objectMap.remove("lastupdTime");
            objectMap.remove("lastupdMan");

            map.put("businessData", objectMap);
            map.put("taskId", taskId);

            return map;
        } catch (IllegalAccessException e) {
            throw new ParamException("获取社团年审申请单失败");
        }
    }

    /**
     * 提交任务
     *
     * @param submitTaskBean
     * @param username
     */
    @Override
    public void saveSubmitTask(SubmitTaskBean submitTaskBean, String username) {
        //调用工作流封装好的方法
        String processInstanceId = sysWorkFlowService.saveSubmitTask(submitTaskBean, username, new HashMap(4));

        //判断是否需要更改申请表状态
        if (sysWorkFlowService.checkProcessIsEnd(processInstanceId)) {
            Map map = new HashMap(4);
            map.put("id", submitTaskBean.getId());
            map.put("deleteStatus", AssConst.DELETING.getCode());
            map.put("editStatus", AssConst.NON_EDITABLE.getCode());
            sysAssAnnMapper.updateStatus(map);
        }
    }

    /**
     * 获取历史的审批信息
     *
     * @param id
     * @return
     */
    @Override
    public Map getHisComment(Integer id) {
        SysAssAnn sysAssAnn = sysAssAnnMapper.selectByPrimaryKey(id);
        String objId = sysAssAnn.getClass().getSimpleName() + "." + id;

        Map<String, Object> map = sysWorkFlowService.findCommentByObjId(objId);
        map.put("businessData", sysAssAnn);
        return map;
    }

    /**
     * 修改社团年审申请的状态
     *
     * @param map
     */
    @Override
    public void updateStatus(Map map) {
        sysAssAnnMapper.updateStatus(map);
    }

    /**
     * 审批不通过
     *
     * @param map
     * @param sysAssAnn
     */
    @Override
    public void auditNotPass(Map map, SysAssAnn sysAssAnn) {
        sysAssAnnMapper.updateStatus(map);
        sysUserService.updateStatusByAssId(sysAssAnn.getAssId(), sysAssAnn.getInsertMan());
        sysAssService.updateStatus(sysAssAnn.getAssId(), sysAssAnn.getInsertMan());
    }
}
